package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.utils.IdGenerator;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class MovementsApiImpl implements MovementsApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdGenerator idGenerator;

    @Override
    public PageResult recommendPublish(Long userId, Integer page, Integer pagesize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        //根据发表时间排序
        query.with(Sort.by(Sort.Order.desc("created")));
        //分页条件
        query.with(PageRequest.of(page-1,pagesize));
        //查询推荐动态列表
        List<RecommendQuanZi> zis = mongoTemplate.find(query, RecommendQuanZi.class);
        System.out.println(zis);
        ArrayList<Publish> publishList = new ArrayList<>();
        for (RecommendQuanZi zi : zis) {
            Publish publish = mongoTemplate.findById(zi.getPublishId(), Publish.class);
            publishList.add(publish);
        }
        //查询总数量
        long count = mongoTemplate.count(query, RecommendQuanZi.class);
        //计算总页数
        int pages = (int) Math.ceil(count*0.1/pagesize);
        //把数据封装到PageResult
        PageResult pageResult = new PageResult<Publish>();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setPages(pages);
        pageResult.setCounts((int) count);
        pageResult.setItems(publishList);
        return pageResult;
    }

    @Override
    public String addMovements(Publish publish) {
        //存到动态列表里
        publish.setId(ObjectId.get());
        publish.setCreated(System.currentTimeMillis());
        publish.setPid(idGenerator.nextId("publish"));
        publish.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(publish);
        //存到自己相册列表中
        Album album = new Album();
        album.setCreated(System.currentTimeMillis());
        album.setId(ObjectId.get());
        album.setPublishId(publish.getId());
        mongoTemplate.insert(album,"quanzi_album_"+publish.getUserId());
        //存到所有好友的时间线列表中
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        for (Friend friend : friends) {
            TimeLine timeLine = new TimeLine();
            timeLine.setCreated(System.currentTimeMillis());
            timeLine.setId(ObjectId.get());
            timeLine.setUserId(publish.getUserId());
            timeLine.setPublishId(publish.getId());
            mongoTemplate.insert(timeLine,"quanzi_time_line_"+friend.getFriendId());
        }

        return publish.getId().toHexString();
    }

    @Override
    public PageResult friendMovements(Long userId,Integer page, Integer pagesize) {
        //找到当前用户的时间线表  里边都是其好友的动态信息
        Query query = new Query();
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page-1,pagesize ));
        List<TimeLine> timeLines = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        long count = mongoTemplate.count(query, "quanzi_time_line_" + userId);
        ArrayList<Publish> publishList = new ArrayList<>();
        for (TimeLine timeLine : timeLines) {
            Publish publish = mongoTemplate.findById(timeLine.getPublishId(), Publish.class);
            publishList.add(publish);
        }
        int pages = (int) Math.ceil(count*0.1/pagesize);
        PageResult pageResult = new PageResult<Publish>();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setPages(pages);
        pageResult.setCounts((int) count);
        pageResult.setItems(publishList);

        //再循环查询好友发布的动态
        return pageResult;
    }

    /**
     * 我的动态
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findMyMovements(Long userId, Integer page, Integer pagesize) {
        Query query = new Query();
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page-1,pagesize));
        List<Album> albums = mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        ArrayList<Publish> publishList = new ArrayList<>();
            for (Album album : albums) {
                Publish publish = mongoTemplate.findById(album.getPublishId(), Publish.class);
                publishList.add(publish);
            }
        long count = mongoTemplate.count(query, Album.class, "quanzi_album_" + userId);
        int pages = (int) Math.ceil(count*1.0/pagesize);
        if (publishList!=null){

            return new PageResult<Publish>((int) count,pagesize,pages,page,publishList);
        }
        return new PageResult<Publish>((int) count,pagesize,pages,page,new ArrayList<>());


    }

    @Override
    public Publish oneMovment(String publishId) {
        return mongoTemplate.findById(publishId, Publish.class);

    }


}
